//
//  ShoppingCarViewController.m
//  CenturyInterconnection
//
//  Created by Tian Wei You on 16/4/11.
//  Copyright © 2016年 Shanghai DuRui Information Technology Company. All rights reserved.
//

#import "ShoppingCarViewController.h"
#import "ShoppingCarTableViewCell.h"
#import "ShoppingListViewController.h"
#import "CommodityDetailsTableViewController.h"
#import "otherButton.h"
#import "RegisterViewController.h"
#import "ShoppingCarModel.h"

#define ShoppingCarCell @"ShoppingCarTableViewCell"

@interface ShoppingCarViewController ()<UITableViewDataSource,UITableViewDelegate,ShoppingCarTableViewCellDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *allDatas;

@property(nonatomic,strong)NSString *priceStr;

@property(nonatomic,strong)NSMutableArray *quantityArray;
@property(nonatomic,assign)CGFloat allPrice;
@property(nonatomic,strong)UILabel *priceLabel;

@property(nonatomic,strong)NSMutableArray*modelAllDatas;
//@property(nonatomic,strong)NSMutableArray*countArray;//每件商品的数量

@property(nonatomic,assign)CGFloat Pricee;  //所以商品的总价
@end

@implementation ShoppingCarViewController

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0,StatusBarHeight+NavigationBarHeight, KScreenWidth, KScreenHeight-ACTUAL_HEIGHT(190)) style:UITableViewStyleGrouped];
        _tableView.delegate=self;
        _tableView.dataSource=self;
    }
    return _tableView;
}

#pragma mark - viewDidLoad
- (void)viewDidLoad {
    self.view.backgroundColor=[UIColor whiteColor];
    
    [super viewDidLoad];
    self.modelAllDatas=[NSMutableArray array];
    
    [self makeNaviButton];
    
    
    
    [self makeView];
    
    self.allDatas=[NSMutableArray array];
    self.quantityArray=[NSMutableArray array];
    
    [self.tableView registerNib:[UINib nibWithNibName:ShoppingCarCell bundle:nil] forCellReuseIdentifier:ShoppingCarCell];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self getDatas];
}




#pragma mark -
-(void)getDatas{
    
    // http://viprunningonline.com/api/index.php?main_page=shopping_cart
    
    NSString * urlStr=[NSString stringWithFormat:@"%@",HTTP_ADDRESS];
    
    NSString * zendIdStr = [[NSString alloc] init];
    
    if ([UserSession instance].cookie) {
        zendIdStr = [UserSession instance].cookie;
    }else{
        zendIdStr = @ "";
    }
    
    NSDictionary *params=@{@"main_page":@"shopping_cart",
                           @"zenid":zendIdStr};
    
    HttpManager*manager=[[HttpManager alloc]init];
    [manager getDataFromNetworkWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
        
        NSString * number=[NSString stringWithFormat:@"%@",data[@"status"]];
        
        if ([number isEqualToString:@"1"]) {
            
            
            //NSLog(@" shopping cart %@ ", data);
            
            
            self.allDatas= data[@"data"][@"cart"];
            self.priceStr= data[@"data"][@"total_price"];
            
            NSMutableString *str=[[NSMutableString alloc]initWithString:self.priceStr];
            [str deleteCharactersInRange:NSMakeRange(0, 1)];
            self.allPrice=[str floatValue];
            
            for (int i=0; i<self.allDatas.count; i++) {
                ShoppingCarModel *model=[[ShoppingCarModel alloc]init];
                [self.modelAllDatas addObject:[model initWithShopCarWithDic:self.allDatas[i]]];
            }
            
            [self.tableView reloadData];
            [self makeView];
        }
    }];
    
}

#pragma mark -
-(void)makeNaviButton{
    
    UIButton * titleButton=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, ACTUAL_WIDTH(180), ACTUAL_HEIGHT(30))];
    [titleButton setTitle:@"Shopping Bag" forState:0];
    UIBarButtonItem * item= [[UIBarButtonItem alloc]initWithCustomView:titleButton];
    self.navigationItem.leftBarButtonItem=item;
    
    UIButton * forkButton=[[UIButton alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(320), 0, ACTUAL_WIDTH(30), ACTUAL_HEIGHT(30))];
    [forkButton setImage:[UIImage imageNamed:@"nav_close"] forState:0];
    [forkButton addTarget:self action:@selector(comeBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * item1 = [[UIBarButtonItem alloc]initWithCustomView:forkButton];
    self.navigationItem.rightBarButtonItem=item1;
}

-(void)makeView{
    
    //价格
    _priceLabel=[[UILabel alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(20),KScreenHeight-ACTUAL_HEIGHT(110),KScreenWidth-ACTUAL_WIDTH(40), ACTUAL_HEIGHT(30))];
    _priceLabel.textAlignment=2;
    _priceLabel.text=self.priceStr;
    _priceLabel.font=[UIFont systemFontOfSize:22];
    [self.view addSubview:_priceLabel];
    
    UIButton *progessOrderButton=[[UIButton alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(25), KScreenHeight-ACTUAL_HEIGHT(70), ACTUAL_WIDTH(325), ACTUAL_HEIGHT(50))];
    [progessOrderButton setTitle:@"PROCESS ORDER" forState:0];
    progessOrderButton.backgroundColor=[UIColor blackColor];
    [progessOrderButton addTarget:self action:@selector(gotoNext) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:progessOrderButton];
    
    if (self.allDatas.count==0) {
        UILabel *noProductsLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, ACTUAL_HEIGHT(300), KScreenWidth, ACTUAL_HEIGHT(30))];
        noProductsLabel.text=@"No products in shopping bag";
        noProductsLabel.textColor=RGBACOLOR(153, 153, 153, 1);
        noProductsLabel.font = FONT_SYSTEM_28;
        noProductsLabel.textAlignment=1;
        [self.view addSubview:noProductsLabel];
    }else{
        [self.view addSubview:self.tableView];
    }
}

#pragma mark - Pay Progess点击事件
-(void)gotoNext{
    
    //    for (int i; i<self.modelAllDatas.count; i++) {
    //        ShoppingCarModel*model=self.modelAllDatas[i];
    //        NSString *str=[NSString stringWithFormat:@"%.0f",model.quantity];
    //        [self.countArray addObject:str];
    //    }
    
    
    if (self.allDatas.count==0) {
        
        [JRToast showWithText:@"Shopping cart is empty！"];
        return;
    }
    
    if ([UserSession instance].isLogin==NO) {
        
        [UserSession instance].isGotoPayment=YES;
        RegisterViewController *vc=[[RegisterViewController alloc]init];
        vc.isShopVCPush = YES;
        vc.shoppingCartArray=self.allDatas;
        vc.otherAllpriceStr=self.priceLabel.text;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else{
        
        ShoppingListViewController *vc=[[ShoppingListViewController alloc]init];
        vc.cartArray=self.allDatas;
        vc.allPrice=self.priceLabel.text;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    
}

#pragma mark - 返回事件
-(void)comeBack{
    [self.navigationController popToRootViewControllerAnimated:YES];
    [[SlideNavigationController sharedInstance].rightMenu viewWillAppear:YES];
}

#pragma mark - TableView设置

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 165;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.00001;
}

#pragma mark -
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.allDatas.count;
    
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ShoppingCarTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:ShoppingCarCell];
    cell.delegate=self;
    cell.indexPath=indexPath;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (self.allDatas.count>0) {
        
        UIImageView *imageView1=[cell viewWithTag:1];
        imageView1.backgroundColor=[UIColor whiteColor];
        [imageView1 sd_setImageWithURL:[NSURL URLWithString:self.allDatas[indexPath.row][@"products_image"]] placeholderImage:nil];
        imageView1.clipsToBounds = YES;
        imageView1.contentMode = UIViewContentModeScaleAspectFit;
        //
        UILabel *label2=[cell viewWithTag:2];
        label2.font = FONT_SYSTEM_28;
        label2.text=self.allDatas[indexPath.row][@"products_name"];
        
        //
        UILabel *label3=[cell viewWithTag:3];
        if (KScreenWidth == 320) {
            label3.font = [UIFont systemFontOfSize:11];
        }else{
            label3.font = FONT_SYSTEM_24;
        }
        
        if ([self.allDatas[indexPath.row][@"attributes"] count]==0) {
            label3.text=@"";
        }else{
            label3.text=self.allDatas[indexPath.row][@"attributes"][0][@"products_options_values_name"];
        }
        
        //
        UILabel *label4=[cell viewWithTag:4];
        if (KScreenWidth == 320) {
            label4.font = [UIFont systemFontOfSize:14];
        }
        label4.text=self.allDatas[indexPath.row][@"format_price"];
        
        //view
        UIButton *button5=[cell viewWithTag:5];
        button5.tag=indexPath.row+1000;
        [button5 addTarget:self action:@selector(comeBackToProductsDetails:) forControlEvents:UIControlEventTouchUpInside];
        
        //delete
        otherButton *button6=[cell viewWithTag:6];
        button6.tagg=indexPath.row;
        [button6 addTarget:self action:@selector(deleteTheLine:) forControlEvents:UIControlEventTouchUpInside];
        
        //
        ShoppingCarModel *model=self.modelAllDatas[indexPath.row];
        cell.addNum.numberString=[NSString stringWithFormat:@"%.0f",model.quantity];
        
    }
    return cell;
}

#pragma mark - Cell“view”的点击事件
-(void)comeBackToProductsDetails:(UIButton*)bt1{

    CommodityDetailsTableViewController *vc=[[CommodityDetailsTableViewController alloc]init];
    vc.idStr=self.allDatas[bt1.tag-1000][@"products_id"];
    vc.isShoppingVCPush = YES;
    vc.imgUrlStr = self.allDatas[bt1.tag-1000][@"products_image"];
    [self.navigationController pushViewController:vc animated:YES];


}


#pragma mark -
//每个Cell里“delete”的点击事件
-(void)deleteTheLine:(otherButton*)bt2{
    
    NSLog(@"shangchur");
    NSMutableArray * arr_a = [NSMutableArray arrayWithArray:self.modelAllDatas];
    [arr_a removeObject:self.modelAllDatas[bt2.tagg]];
    self.modelAllDatas = arr_a;
    
    //http://viprunningonline.com/api/index.php?main_page=shopping_cart
    NSString*urlStr=[NSString stringWithFormat:@"%@main_page=cart_actions",HTTP_ADDRESS];
    
    NSDictionary*params=@{@"act":@"remove",
                          @"basket_id":self.allDatas[bt2.tagg][@"id"],
                          @"zenid":[UserSession instance].cookie};
    
    HttpManager*manager=[[HttpManager alloc]init];
    
    [manager postDataFromNetworkWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
        
        NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
        
        if ([number isEqualToString:@"1"]) {
            [JRToast showWithText:@"Delete the success！"];
            
            NSDictionary * bt = self.allDatas[bt2.tagg];
            
            NSMutableArray * temp =[NSMutableArray arrayWithArray:self.allDatas];
            [temp removeObject:bt];
            self.allDatas = temp;
            
            [self.tableView reloadData];
            
            [self CalAllPrice];
            
        }else{
            
            [JRToast showWithText:data[@"status_message"]];
            
        }
    }];
}

//add数量
-(void)delegateForAddNumberString:(NSString *)NumberStr andIndexPath:(NSIndexPath *)indexPath{
    
    //NSLog(@"加");
    ShoppingCarModel *model= self.modelAllDatas[indexPath.row];
    model.quantity = [NumberStr floatValue];
    
    NSDictionary * att_index =  model.attributes[0];
    
    id id1 = [att_index valueForKey:@"options_id"];
    id id2 = [att_index valueForKey:@"options_values_id"];
    
    NSString * str = [NSString stringWithFormat:@"id[%@]",id1];
    NSString * options_values_id = [NSString stringWithFormat:@"%@",id2];
    
    // http://viprunningonline.com/api/index.php?main_page=cart_actions
    NSString*urlStr=[NSString stringWithFormat:@"%@main_page=cart_actions",HTTP_ADDRESS];
    
    NSDictionary*params=@{@"act":@"update",
                          str:options_values_id,
                          @"products_id":model.products_id,
                          @"cart_quantity":NumberStr,
                          @"zenid":[UserSession instance].cookie};
    
    //NSLog(@"%@",params);
    
    
    HttpManager*manager=[[HttpManager alloc]init];
    
    [manager postDataFromNetworkWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
        
        //NSLog(@" data: %@",data);
    }];
    [self CalAllPrice];
}

//删除数量
-(void)delegateForSubNumberString:(NSString *)NumberStr andIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"减少%@",NumberStr);
    
    
    ShoppingCarModel * model = self.modelAllDatas[indexPath.row];
    model.quantity=[NumberStr floatValue];
    
    NSDictionary * att_index =  model.attributes[0];
    
    id id1 = [att_index valueForKey:@"options_id"];
    id id2 = [att_index valueForKey:@"options_values_id"];
    
    NSString * str = [NSString stringWithFormat:@"id[%@]",id1];
    NSString * options_values_id = [NSString stringWithFormat:@"%@",id2];
    
    
    // http://viprunningonline.com/api/index.php?main_page=cart_actions
    NSString*urlStr=[NSString stringWithFormat:@"%@main_page=cart_actions",HTTP_ADDRESS];
    
    NSDictionary*params=@{@"act":@"update",
                          @"products_id":model.products_id,
                          str:options_values_id,
                          @"cart_quantity":NumberStr,
                          @"zenid":[UserSession instance].cookie};
    
    
    //NSLog(@"%@",params);
    
    HttpManager*manager=[[HttpManager alloc]init];
    
    [manager postDataFromNetworkWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
        NSLog(@" data: %@",data);
        
    }];
    [self CalAllPrice];
    
}


#pragma mark - 计算总价
-(void)CalAllPrice{
    
    self.Pricee = 0;
    
    for (int i=0; i<self.modelAllDatas.count; i++) {
        ShoppingCarModel*model=[[ShoppingCarModel alloc]init];
        model=self.modelAllDatas[i];
        //单件商品价格
        CGFloat money=model.quantity*[[self stringByReplaceWithStr:model.format_price]floatValue];
        self.Pricee=self.Pricee+money;

    }
    self.priceLabel.text=[NSString stringWithFormat:@"%@%.2f",[self stringWithMoney],self.Pricee];
}

-(NSString *)stringByReplaceWithStr:(NSString *)string
{
    NSString * str = [[[[[[string stringByReplacingOccurrencesOfString:@"$" withString:@""]stringByReplacingOccurrencesOfString:@"," withString:@""]stringByReplacingOccurrencesOfString:@"CAD" withString:@""]stringByReplacingOccurrencesOfString:@"£" withString:@""] stringByReplacingOccurrencesOfString:@"AU" withString:@""] stringByReplacingOccurrencesOfString:@"€" withString:@""];
    return str;
}
-(NSString *)stringWithMoney
{
    NSString * str;
    NSString * moneyStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"MONEYINDEX"];
    NSInteger index ;
    if ([moneyStr isEqualToString:@""]) {
        index = 1;
    }else{
        index = [moneyStr integerValue];
    }
    if (index == 0) {
        str = @"CAD$";
    }else if (index == 1){
        str = @"$";
    }else if (index == 2){
        str = @"£";
    }else if (index == 3){
        str = @"AU$";
    }else{
        str = @"€";
    }
    return str;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
